#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>

using namespace std;
using namespace cv;

extern "C"{
// メモリ上のJPEGデータを読み込んで
// Cannyでエッジ検出
// 結果はstoreに保存する
// storeの先頭4バイトにPNGデータサイズ
// storeの5バイト目以降にPNGデータを格納する
void cv_interface(uchar *image, int size, uchar *store)
{
	vector<uchar>		in_buff, out_buff;
	vector<uchar>::iterator	it;

	//Mat	in(image);
	Mat	in_image(Size(1, size), CV_8UC1, image);
	Mat	src, dest;

	//load jpeg
	src = imdecode(in_image, 0);
	if(!src.data)
	{
		fprintf(stderr, "imdecode error\n");
		return;
	}

	//canny edge
	Canny(src, dest, 50.0, 200.0);
	//threshold(src, dest, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

	//output
	imencode(".png", dest, out_buff);

	int buff_size = out_buff.size();
	//printf("buff.size() = %d\n", buff_size);
	memcpy(store, &buff_size, 4);
      	store += 4; 

	for(it=out_buff.begin() ; it!=out_buff.end() ; it++)
	{
		*store = *it;
		store++;
	}
}
}

#ifdef STANDALONE
int main()
{
	FILE	*fp;
	uchar	in_buff[50000];
	uchar	out_buff[50000];
	int	in_size, out_size;

	fp = fopen("image.jpg", "rb");
	if( fp == NULL )
	{
		fprintf(stderr, "[ERROR] Can't open in_file\n");
		return EXIT_FAILURE;
	}
	in_size = fread(in_buff, sizeof(uchar), 50000, fp);
	printf("read length : %d\n", in_size);
	fclose(fp);

	cv_interface(in_buff, in_size, out_buff);

	memcpy(&out_size, out_buff, 4);
	printf("out_buff size = %d\n", out_size);

	fp = fopen("image.png", "wb");
	if( fp == NULL )
	{
		fprintf(stderr, "[ERROR] Can't open out_file\n");
		return EXIT_FAILURE;
	}
	fwrite(&out_buff[4], sizeof(uchar), out_size, fp);
	fclose(fp);
	
	return EXIT_SUCCESS;
}
#endif

